#!/usr/bin/env python3
"""
检查同步任务配置
"""

import pymysql
import sys

# 数据库配置
DB_CONFIG = {
    'host': '192.168.37.11',
    'port': 3306,
    'user': 'root',
    'password': '123456',
    'database': 'data_plexus',
    'charset': 'utf8mb4'
}

def check_sync_tasks():
    """检查同步任务配置"""
    connection = None
    try:
        # 连接数据库
        print("连接数据库...")
        connection = pymysql.connect(**DB_CONFIG)
        cursor = connection.cursor()
        
        print(f"成功连接到数据库: {DB_CONFIG['host']}:{DB_CONFIG['port']}/{DB_CONFIG['database']}")
        
        # 查询同步任务
        print("\n查询同步任务配置...")
        cursor.execute("""
            SELECT 
                id,
                name,
                display_name,
                sync_type,
                batch_size,
                target_type,
                is_active,
                source_table_name,
                source_datasource_id,
                target_datasource_id
            FROM dp_sync_tasks 
            WHERE is_deleted = FALSE
            ORDER BY id
        """)
        
        tasks = cursor.fetchall()
        if tasks:
            print(f"找到 {len(tasks)} 个同步任务:")
            print("ID\t名称\t\t\t显示名称\t\t同步类型\tbatch_size\t目标类型\t状态\t源表")
            print("-" * 120)
            for task in tasks:
                id, name, display_name, sync_type, batch_size, target_type, is_active, source_table, source_ds_id, target_ds_id = task
                status = "启用" if is_active else "禁用"
                print(f"{id}\t{name[:15]:<15}\t{display_name[:15]:<15}\t{sync_type}\t{batch_size}\t\t{target_type}\t{status}\t{source_table}")
        else:
            print("没有找到同步任务")
            return
        
        # 查询最近的执行记录
        print("\n查询最近的执行记录...")
        cursor.execute("""
            SELECT 
                e.id,
                e.task_id,
                t.name as task_name,
                e.status,
                e.total_records,
                e.processed_records,
                e.success_records,
                e.failed_records,
                e.started_at,
                e.completed_at,
                e.error_message
            FROM dp_sync_executions e
            JOIN dp_sync_tasks t ON e.task_id = t.id
            ORDER BY e.created_at DESC
            LIMIT 10
        """)
        
        executions = cursor.fetchall()
        if executions:
            print(f"最近 {len(executions)} 次执行记录:")
            print("执行ID\t任务ID\t任务名称\t\t状态\t\t总记录\t处理记录\t成功记录\t失败记录\t开始时间\t\t\t错误信息")
            print("-" * 150)
            for execution in executions:
                exec_id, task_id, task_name, status, total, processed, success, failed, started, completed, error = execution
                error_msg = (error[:30] + "...") if error and len(error) > 30 else (error or "")
                started_str = started.strftime("%Y-%m-%d %H:%M:%S") if started else ""
                print(f"{exec_id}\t{task_id}\t{task_name[:15]:<15}\t{status}\t{total or 0}\t{processed or 0}\t{success or 0}\t{failed or 0}\t{started_str}\t{error_msg}")
        else:
            print("没有找到执行记录")
        
        # 查询最近的日志
        print("\n查询最近的同步日志...")
        cursor.execute("""
            SELECT 
                l.id,
                l.execution_id,
                l.log_level,
                l.log_message,
                l.batch_number,
                l.created_at
            FROM dp_sync_logs l
            ORDER BY l.created_at DESC
            LIMIT 20
        """)
        
        logs = cursor.fetchall()
        if logs:
            print(f"最近 {len(logs)} 条日志:")
            print("日志ID\t执行ID\t级别\t\t批次\t时间\t\t\t\t日志消息")
            print("-" * 120)
            for log in logs:
                log_id, exec_id, level, message, batch_num, created = log
                created_str = created.strftime("%Y-%m-%d %H:%M:%S") if created else ""
                message_short = (message[:50] + "...") if message and len(message) > 50 else (message or "")
                print(f"{log_id}\t{exec_id}\t{level}\t{batch_num or ''}\t{created_str}\t{message_short}")
        else:
            print("没有找到日志记录")
        
        return True
        
    except Exception as e:
        print(f"检查失败: {e}")
        return False
        
    finally:
        if connection:
            connection.close()
            print("\n数据库连接已关闭")

def main():
    """主函数"""
    print("DataPlexus 同步任务配置检查工具")
    print("=" * 50)
    
    success = check_sync_tasks()
    
    if success:
        print("\n✓ 检查完成!")
        sys.exit(0)
    else:
        print("\n✗ 检查失败!")
        sys.exit(1)

if __name__ == "__main__":
    main()
